package klimuts.periodicals.catalog.actions;

import java.util.Map;

import klimuts.periodicals.catalog.Catalog;
import klimuts.periodicals.data.DataSource;
import klimuts.periodicals.user.Cart;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

/**
 *   Action prepare periodicals data for catalog page and show this page after all.
 * For reduce data base requests all periodicals will be once saved in session and   
 * next time will be getting from it. 
 * If some periodicals is already exists in users cart, it periodicals will be
 * removed from view. 
 * @author Klimuts Siarhei
 */
public class ShowCatalog extends ActionSupport implements SessionAware {
	private Map<String,Object> session;
	private Catalog periodicals;
	private int count;
	// TODO remove form submit
	
	/**
	 *   Here if catalog not exists in session then will be created query to database to save all periodicals in
	 * session. Else periodicals will be updated only when max(id) in database is bigger than id of last
	 * periodical in catalog.
	 */
	public String execute() throws Exception {
		Catalog catalog=(Catalog)session.get("catalog");
		Cart cart=(Cart)session.get("cart");
		
		if ((catalog==null)||(catalog.getLast().getId()<DataSource.getMax("Periodical"))) {
			catalog=DataSource.getPeriodicals();
			session.put("catalog", catalog);
		}
		periodicals=(Catalog)catalog.clone();
		// don't show me items already contains in my cart 
		if (cart!=null)
			periodicals.removeAll(cart);
		count=periodicals.size();
		return "success";
	}

	public Catalog getPeriodicals() {
		return periodicals;
	}

	public void setPeriodicals(Catalog periodicals) {
		this.periodicals = periodicals;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
